package com.example.daxiguaforharmony.slice;

import com.alibaba.fastjson.JSON;
import com.example.daxiguaforharmony.MainAbility;
import com.example.daxiguaforharmony.ResourceTable;
import com.example.daxiguaforharmony.ResultsAbility;
import com.example.daxiguaforharmony.SharedService;
import com.example.daxiguaforharmony.game.AssetManager;
import com.example.daxiguaforharmony.game.FruitsVO;
import com.example.daxiguaforharmony.game.GameScene;
import com.example.daxiguaforharmony.game.core.GameEventHander;
import com.example.daxiguaforharmony.game.core.base.DisplayObjectContainer;
import com.example.daxiguaforharmony.game.core.base.ITouchCallback;
import com.example.daxiguaforharmony.game.core.component.Button;
import com.example.daxiguaforharmony.game.core.game.SceneBase;
import com.example.daxiguaforharmony.game.core.renderers.Label;
import com.example.daxiguaforharmony.game.core.renderers.Sprite;
import com.example.daxiguaforharmony.manager.CrossDeviceManager;
import com.example.daxiguaforharmony.ui.DeviceSelectDialog;
import com.example.daxiguaforharmony.utils.Audio;
import com.example.daxiguaforharmony.utils.DbKvManager;
import com.example.daxiguaforharmony.utils.ImageUtil;
import com.example.daxiguaforharmony.utils.LogUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.FormException;
import ohos.aafwk.ability.IAbilityContinuation;
import ohos.aafwk.ability.ProviderFormInfo;
import ohos.aafwk.ability.continuation.ExtraParams;
import ohos.aafwk.ability.continuation.IContinuationDeviceCallback;
import ohos.aafwk.ability.continuation.IContinuationRegisterManager;
import ohos.aafwk.ability.continuation.RequestCallback;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.components.webengine.WebView;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.WindowManager;
import ohos.bundle.AbilityInfo;
import ohos.bundle.IBundleManager;
//import ohos.data.distributed.common.KvManagerConfig;
//import ohos.data.distributed.common.KvManagerFactory;
import ohos.data.distributed.common.Entry;
import ohos.data.distributed.common.Value;
import ohos.distributedschedule.interwork.DeviceInfo;
import ohos.distributedschedule.interwork.DeviceManager;
import ohos.eventhandler.EventRunner;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.TouchEvent;
import ohos.rpc.RemoteException;

import java.util.*;

/**
 * Full screen ability slice
 */
public class GameAbilitySlice extends AbilitySlice implements IAbilityContinuation, GameScene.GameSceneCallback {
    //private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "MainAbilitySlice");
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(HiLog.LOG_APP,0x0001,"获取跳转结果测试");
    private static final String TAG = GameAbilitySlice.class.getSimpleName();

    private DirectionalLayout _layout = null;
    private GameScene _scene = null;
    private GameEventHander _gameHandler = null;

    private Button btnFind = null;
    private String data = null;
    DbKvManager dbKvManager;
    String deviceId = "";
    List<String> deviceList;
    public static final String INTENT_IS_SHOW_START = "intent_isShowStart";
    public static final String INTENT_MY_SCORE = "intent_myScore";
    public static final String INTENT_MY_FRUITS = "intent_myFruits";
    private String isShowStart;
    private String myScore;
    private String myFruits;

    ComponentProvider componentProvider;
    private long formId;
    String formName;
    Image imgFind;

    // 流转应用包名
    private String BUNDLE_NAME = getBundleName();
    // 注册流转任务管理服务后返回的Ability token
    private int abilityToken;
    // 用户在设备列表中选择设备后返回的设备ID
    private String selectDeviceId;
    // 用户是否已发起可拉回流转流程
    private boolean isReversibly = false;
    // 获取流转任务管理服务管理类
    private IContinuationRegisterManager continuationRegisterManager;
    // 设置流转任务管理服务设备状态变更的回调
    private IContinuationDeviceCallback callback = new IContinuationDeviceCallback() {
        @Override
        public void onDeviceConnectDone(String deviceId, String deviceType) {
            // 在用户选择设备后设置设备ID
            selectDeviceId = deviceId;
        }

        @Override
        public void onDeviceDisconnectDone(String deviceId) {
        }
    };
    // 设置注册流转任务管理服务回调
    private RequestCallback requestCallback = new RequestCallback() {
        @Override
        public void onResult(int result) {
            abilityToken = result;
        }
    };

    @Override
    public void onStart(Intent intent) {
        //requestPermissionsFromUser(new String[]{"ohos.permission.DISTRIBUTED_DATASYNC","ohos.permission.GET_DISTRIBUTED_DEVICE_INFO", "ohos.permission.servicebus.ACCESS_SERVICE", "com.huawei.hwddmp.servicebus.BIND_SERVICE"}, 0);
        if (verifySelfPermission("ohos.permission.DISTRIBUTED_DATASYNC") != IBundleManager.PERMISSION_GRANTED) {
            // 应用未被授予权限
            if (canRequestPermission("ohos.permission.DISTRIBUTED_DATASYNC")) {
                // 是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示)
                requestPermissionsFromUser(new String[]{"ohos.permission.DISTRIBUTED_DATASYNC","ohos.permission.DISTRIBUTED_DATA","ohos.permission.GET_DISTRIBUTED_DEVICE_INFO", "ohos.permission.servicebus.ACCESS_SERVICE", "com.huawei.hwddmp.servicebus.BIND_SERVICE"}, 1);
            } else {
                // 显示应用需要权限的理由，提示用户进入设置授权
            }
        } else {
            // 权限已被授予
        }
        super.onStart(intent);

        // hide status bar
        this.getWindow().addFlags(WindowManager.LayoutConfig.MARK_ALLOW_EXTEND_LAYOUT);
        this.getWindow().addFlags(WindowManager.LayoutConfig.MARK_FULL_SCREEN);

//        WindowManager.getInstance().getTopWindow().get().setStatusBarColor(Color.BLUE.getValue()); // 设置状态栏颜色
//        getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_NAVIGATION);
//        getWindow().addFlags(WindowManager.LayoutConfig.MARK_FULL_SCREEN);//隐藏状态栏
//        getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_STATUS);//沉浸式状态栏
//        WindowManager.getInstance().getTopWindow().get().setStatusBarVisibility(Component.HIDE);   //设置状态栏隐藏

        this._layout = new DirectionalLayout(this);
        this._layout.setLayoutConfig((new ComponentContainer.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT,ComponentContainer.LayoutConfig.MATCH_PARENT)));

        this.setUIContent(this._layout);

        imgFind = new Image(getContext());

        isShowStart = intent.getStringParam(INTENT_IS_SHOW_START);//是否启动屏
        myScore = intent.getStringParam(INTENT_MY_SCORE);//当前分数
        myFruits = intent.getStringParam(INTENT_MY_FRUITS);//当前水果
        //isShowStart = isShowStart.isEmpty()?"0":"1";
        //myScore = myScore.isEmpty()?"0":myScore;
        System.out.println("onStart isShowStart===="+isShowStart+" myScore===="+myScore);
        if(isShowStart.equals("1"))
        {
            Audio.getInstance().init(this.getContext());

            String[] audioAssets = new String[2];
            audioAssets[0] = "luodi.mp3";
            audioAssets[1] = "hecheng1.mp3";
            Audio.getInstance().preloadAudio(audioAssets, false);

            AssetManager.getInstance().loadFruits(this.getContext());//加载水果

        }
        //AssetManager.getInstance().loadFruits(this.getContext());
        CrossDeviceManager.getInstance().init(this);

        EventRunner runner = EventRunner.current();
        this._gameHandler = new GameEventHander(runner, this._layout, this);
        this._gameHandler.startup();

        dbKvManager = DbKvManager.getDbKvManager(this.getApplicationContext());
        deviceId = this.dbKvManager.getDeviceId();
        deviceList = dbKvManager.getDeviceList();

        componentProvider = new ComponentProvider(ResourceTable.Layout_form_image_with_information_widget_2_2, this);

        continuationRegisterManager = getContinuationRegisterManager();

        //增加过滤条件
        ExtraParams params = new ExtraParams();
        String[] devTypes = new String[]{ExtraParams.DEVICETYPE_SMART_PAD, ExtraParams.DEVICETYPE_SMART_PHONE};
        params.setDevType(devTypes);
        String jsonParams = "{'filter':{'commonFilter':{'system':{'harmonyVersion':'2.0.0'},'groupType':'1|256','curComType': 0x00030004,'faFilter':'{\"targetBundleName\": \"com.example.daxiguaforharmony\"}'}},'transferScene':1,'remoteAuthenticationDescription': '拉起HiVision扫描弹框描述','remoteAuthenticationPicture':''}";
        params.setJsonParams(jsonParams);

        // 注册流转任务管理服务
        try{
            continuationRegisterManager.register(BUNDLE_NAME, params, callback, requestCallback);
        }
        catch (Exception err){
            System.out.println("注册流转任务管理服务error==="+err.getMessage());
        }


    }

    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) {
        super.onOrientationChanged(displayOrientation);
    }

    @Override
    public void onActive() {
        super.onActive();
        CrossDeviceManager.getInstance().connectRemoteServices();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
        if (this._gameHandler != null) this._gameHandler.startTimer();
    }

    @Override
    public void onBackground() {
        super.onBackground();
        if (this._gameHandler != null) this._gameHandler.stopTimer();
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        HiLog.info(LABEL_LOG,"请求code:"+requestCode);
        HiLog.info(LABEL_LOG,"响应code:"+resultCode);
        if(requestCode==100)
        {
            HiLog.info(LABEL_LOG,"请求code匹配");
            if(resultData!=null)
            {
                HiLog.info(LABEL_LOG,"请求结果:"+resultData.getStringParam("transVal"));
            }
        }
        super.onAbilityResult(requestCode, resultCode, resultData);
    }

    @Override
    public void onStop() {
        super.onStop();
        // 解注册流转任务管理服务
        continuationRegisterManager.unregister(abilityToken, null);
        // 断开流转任务管理服务连接
        continuationRegisterManager.disconnect();
    }

    @Override
    protected void onResult(int requestCode, Intent resultIntent) {
        HiLog.info(LABEL_LOG,"请求code=====:"+requestCode);
        System.out.println("请求code=====:"+requestCode);
        if (requestCode == 100) {
            // Process resultIntent here.
            HiLog.info(LABEL_LOG,"请求code匹配=====");
            System.out.println("请求code匹配=====:"+requestCode);
            if(resultIntent.getParam("transVal")!=null)
            {
                HiLog.info(LABEL_LOG,"请求结果=====:"+resultIntent.getStringParam("transVal"));
                System.out.println("请求结果=====:"+resultIntent.getStringParam("transVal"));
            }
        }
    }


    // ======================== IAbilityContinuation -- 多设备协同回调  ==================================
    private void showMessage(String msg) {
        ToastDialog toastDialog = new ToastDialog(this);
        toastDialog.setText(msg);
        toastDialog.show();
    }

    @Override
    public boolean onStartContinuation() {
        //return CrossDeviceManager.getInstance().onStartContinuation();
        showMessage("ContinueAbility Start");
        return true;
    }

    @Override
    public boolean onSaveData(IntentParams intentParams) {
        intentParams.setParam("data","remote");
        //return CrossDeviceManager.getInstance().onSaveData(intentParams);
        String exampleData = String.valueOf(System.currentTimeMillis());
        intentParams.setParam("continueParam", exampleData);
        return true;
    }

    @Override
    public boolean onRestoreData(IntentParams intentParams) {
        // 远端FA迁移传来的状态数据，开发者可以按照特定的场景对这些数据进行处理
        data = intentParams.getParam("data").toString();
        //return CrossDeviceManager.getInstance().onRestoreData(intentParams);
        // 远端FA迁移传来的状态数据，开发者可以按照特定的场景对这些数据进行处理
        Object data = intentParams.getParam("continueParam");
        return true;
    }

    @Override
    public void onCompleteContinuation(int i) {
        // 开发者可以根据业务需要，提示用户迁移完成，关闭本端FA
        //CrossDeviceManager.getInstance().onCompleteContinuation(i);
        showMessage("ContinueAbility Done");
        if (!isReversibly) {
            terminateAbility();
        }
    }

    // ======================== GameScene.GameSceneCallback -- 游戏场景回调 =============================

    @Override
    public void onInitComplete(SceneBase scene) {
        this._scene = (GameScene)scene;

        setDeviceScore(0, "玩家1",false);//玩家1
        setDeviceScore(1, "玩家2",false);//玩家2
        setDeviceScore(2, "玩家3",false);//玩家3
        setDeviceScore(3, "玩家4",false);//玩家4
        setDeviceScore(4, "玩家5",false);//玩家5

        if(isShowStart.equals("1")) {
            System.out.println("onInitComplete isShowStart===="+isShowStart+" myScore===="+myScore);
            int mscore = Integer.parseInt(myScore);
            System.out.println("onInitComplete mscore==="+mscore);
            this._scene.startGame(); // 跳过play界面, 直接开始游戏
            this._scene.setScore(mscore);

            //List<FruitsVO> fruitsVOList = new ArrayList<>();
            LogUtil.info(TAG, "onInitComplete myFruits==="+myFruits);
            if(!myFruits.isEmpty()) {
                List<FruitsVO> fruitsVOList = JSON.parseArray(myFruits,FruitsVO.class);
                this._scene.revertFruitsList(fruitsVOList);
            }

            this.onUpdateScore(mscore);


        }

        DisplayObjectContainer container = this._scene.getDisplayContainer();
        float sceneWidth = this._scene.getSceneWidth();
        imgFind = new Image(this.getContext());
        imgFind.setPixelMap(ResourceTable.Media_qianyi);
        Sprite sprite = new Sprite(imgFind.getPixelMapHolder());
        this.btnFind = new Button(sprite);
        sprite.x = sceneWidth - sprite.width / 2;
        sprite.y = sprite.height / 2;
        sprite.scaleX = 0.5f;
        sprite.scaleY = 0.5f;
        //sprite.visible = false;
        container.addChild(sprite);
        this._scene.addTouchHandler(this.btnFind);
        this.btnFind.setTouchCallback(new ITouchCallback() {
            @Override
            public void onTouchEvent(TouchEvent touchEvent) {
                if (touchEvent.getAction() == TouchEvent.PRIMARY_POINT_UP) {
                    //CrossDeviceManager.getInstance().findDevice();
                    findClick();
                    //findClick2();
                }
            }
        });

        startTimer();


    }


    // 定时器，每秒执行一次
    private void startTimer() {
        Timer timer = new Timer();
        timer.schedule(
                new TimerTask() {
                    @Override
                    public void run() {
                        updateScore();;
                    }
                },
                0,
                1000L);//1min
    }

    private void updateScore()
    {
        System.out.println("定时start当前设备数===="+deviceList.size());
        if(deviceList.size()>0)
        {
            dbKvManager.syncDeviceData(deviceList);//多设备同步数据
            System.out.println("定时currentTimeMillis===333==="+System.currentTimeMillis());

            for(int i=0;i<deviceList.size();i++)
            {
                String devName = "userscore_"+deviceList.get(i);
                String score_dev = dbKvManager.read(devName);
                score_dev = score_dev.isEmpty()?"0":score_dev;
                int kk = i+1;
                setDeviceScore(i, "玩家"+kk+":"+score_dev,true);//玩家1
                System.out.println("定时update 玩家得分==="+devName+" score_dev ==="+score_dev);
            }
        }
        System.out.println("定时update end currentTimeMillis===444==="+System.currentTimeMillis());
    }

    @Override
    public void onPlayGame() {
    }

    @Override
    public void onUpdateScore(int score) {
        System.out.println("update score ==="+score);

        System.out.println("currentTimeMillis==111==="+System.currentTimeMillis());

        if(dbKvManager == null)
        {
            dbKvManager = new DbKvManager(this.getContext());
        }

        System.out.println("currentTimeMillis==222==="+System.currentTimeMillis());
        //List<String> deviceList = dbKvManager.getDeviceList();
        System.out.println("当前设备数===="+deviceList.size());
        List<Entry> entryList = new ArrayList<>();
        if(deviceList.size()>0)
        {
            System.out.println("write 玩家自己得分 "+"deviceId ==="+deviceId+"==="+score);
            //dbKvManager.write("userscore_"+deviceId, Integer.toString(score));
            entryList.add(new Entry("score", Value.get(Integer.toString(score))));
            entryList.add(new Entry("userscore_"+deviceId, Value.get(Integer.toString(score))));
            dbKvManager.writeAll(entryList);
            dbKvManager.syncDeviceData(deviceList);//多设备同步数据
            System.out.println("currentTimeMillis===333==="+System.currentTimeMillis());

            for(int i=0;i<deviceList.size();i++)
            {
                String devName = "userscore_"+deviceList.get(i);
                String score_dev = dbKvManager.read(devName);
                score_dev = score_dev.isEmpty()?"0":score_dev;
                int kk = i+1;
                //score = Integer.getInteger(score_dev);
                setDeviceScore(i, "玩家"+kk+":"+score_dev,true);//玩家1
                System.out.println("update 玩家得分==="+devName+" score_dev ==="+score_dev);
            }
            System.out.println("currentTimeMillis===444==="+System.currentTimeMillis());
        }
        else
        {
            //entryList.add(new Entry("score", Value.get(Integer.toString(score))));
            dbKvManager.write("score", Integer.toString(score));

        }
        componentProvider = new ComponentProvider(ResourceTable.Layout_form_image_with_information_widget_2_2, this);
        componentProvider.setText(ResourceTable.Id_text_title, Integer.toString(score));

        System.out.println("currentTimeMillis===555==="+System.currentTimeMillis());


        //this._audio.playAudio2(ResourceTable.Media_test,this);
        System.out.println("update score end得分==="+score);
    }



    @Override
    public void onGameOver(int score) {
        //gameHandler.stopTimer();
        System.out.println("游戏结束======"+score);
        if(dbKvManager == null)
        {
            dbKvManager = new DbKvManager(this.getContext());
        }

        Intent intent = new Intent();
        Operation operation =
                new Intent.OperationBuilder()
                        .withBundleName(getBundleName())
                        .withAbilityName(MainAbility.class.getName())
                        .withAction("action.results")
                        .build();
        intent.setOperation(operation);


        String score1 = String.valueOf(score);
        if(score1.isEmpty())
        {
            score1 = "0";
        }
        System.out.println("onGameOver得分2======="+score1);
        String score_high = dbKvManager.read("score_high");
        score_high = score_high.equals("") ?"0":score_high;

            int high = Integer.parseInt(score_high);
            if(score > high)
            {
                System.out.println("onGameOver更新最高得分======"+score);
                score_high = String.valueOf(score);
                dbKvManager.write("score_high",score_high);
            }

        System.out.println("onGameOver最高得分2======="+score_high);
        String tip = ImageUtil.getGameTip(score,this);

        intent.setParam(ResultsAbilitySlice.INTENT_TITLE, "大西瓜");
        intent.setParam(ResultsAbilitySlice.INTENT_READ, score1);
        intent.setParam(ResultsAbilitySlice.INTENT_LIKE, score_high);
        intent.setParam(ResultsAbilitySlice.INTENT_CONTENT, tip);
        intent.setParam("score", score);

        //present(new ResultsAbilitySlice(), intent);
        startAbility(intent);

        dbKvManager.write("score",Integer.toString(score));
        dbKvManager.write("userscore_"+deviceId,Integer.toString(score));
        dbKvManager.syncDeviceData(deviceList);//多设备同步数据


        componentProvider = new ComponentProvider(ResourceTable.Layout_form_image_with_information_widget_2_2, this.getContext());
        componentProvider.setText(ResourceTable.Id_text_title, score_high);


        System.out.println("游戏结束end======"+score);
        terminate();//销毁窗体
        //terminateAbility();//关闭本端FA
    }

    @Override
    public void onPlayAudio(int audio) {
        System.out.println("游戏声音======"+audio);
        if (audio == 2) {
            Audio.getInstance().playAudio("hecheng1.mp3");
        } else if (audio == 1) {
            Audio.getInstance().playAudio("luodi.mp3");
        }
        System.out.println("游戏声音end======"+audio);
    }

    @Override
    public void onShowToast(String text) {
        ToastDialog toastDialog = new ToastDialog(this.getContext());
        toastDialog.setText(text);
        toastDialog.setAlignment(LayoutAlignment.CENTER);
        toastDialog.show();
    }

    @Override
    public void onOpenPrivacy() {
        Intent intent = new Intent();
        Operation operation =
                new Intent.OperationBuilder()
                        .withBundleName(getBundleName())
                        .withAbilityName(MainAbility.class.getName())
                        .withAction("action.privacy")
                        .build();
        intent.setOperation(operation);
        startAbility(intent);
    }

    @Override
    public void onOpenHelp() {
        Intent intent = new Intent();
        Operation operation =
                new Intent.OperationBuilder()
                        .withBundleName(getBundleName())
                        .withAbilityName(MainAbility.class.getName())
                        .withAction("action.desc")
                        .build();
        intent.setOperation(operation);
        startAbility(intent);
    }

    public void setDeviceScore(int index, String score,boolean isShow) {
        this._scene.setDeviceScore(index, score,isShow);
    }

    public void setVisibleDeviceScore(int index, boolean visible) {
        this._scene.setVisibleDeviceScore(index, visible);
    }

    public void hideAllDeviceScore() {
        this._scene.hideAllDeviceScore();
    }

    public void findClick()
    {
        System.out.println("findClick===");
        myScore = String.valueOf(this._scene.getScore());//this._scene.getScore();
        List<FruitsVO> fruitsVOList = this._scene.getFruitsList();
        System.out.println(fruitsVOList.size()+"===");
        for(int i = 0 ;i < fruitsVOList.size() ; i++){
            FruitsVO fruitsVO = fruitsVOList.get(i);
            System.out.println(fruitsVO);
        }
        myFruits = JSON.toJSONString(fruitsVOList);
        LogUtil.info(TAG, "myFruits==="+myFruits);
        DeviceSelectDialog dialog = new DeviceSelectDialog(this.getContext());
        dialog.setListener(deviceInfo -> {
            LogUtil.info(TAG, "continue button click===");
            LogUtil.debug(TAG, ": device name === " + deviceInfo.getDeviceName().toString());
            System.out.println(TAG + ": device name === " + deviceInfo.getDeviceName().toString());

            try {
                // 开始任务迁移

                //continueAbility();
                //this.continueAbility(deviceInfo.getDeviceId());
                // 远程启动FA
                Intent remoteIntent = new Intent();
// 指定待启动FA的bundleName和abilityName
// 例如：BUNDLE_NAME = "com.huawei.codelab"
//     ABILITY_NAME = "com.huawei.codelab.MainAbility"
// 设置分布式标记，表明当前涉及分布式能力
                Operation operation = new Intent.OperationBuilder().withDeviceId(deviceInfo.getDeviceId())
                        .withBundleName(getBundleName())
                        .withAbilityName(MainAbility.class.getName())
                        .withAction("action.game")
                        .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                        .build();
                remoteIntent.setOperation(operation);
                remoteIntent.setParam(GameAbilitySlice.INTENT_IS_SHOW_START, "1");//不显示启动屏
                remoteIntent.setParam(GameAbilitySlice.INTENT_MY_SCORE, myScore);
                remoteIntent.setParam(GameAbilitySlice.INTENT_MY_FRUITS, myFruits);
                try {
                    // 目标设备是否包含指定FA
                    List<AbilityInfo> abilityInfoList = getBundleManager().queryAbilityByIntent(remoteIntent, 0, 0);
                    if (abilityInfoList != null && !abilityInfoList.isEmpty()) {
                        startAbility(remoteIntent);
                    }
                } catch (RemoteException e) {
                    // 处理异常
                    System.out.println("find click error"+e.getMessage());
                }
                LogUtil.info(TAG, "continue button click end===");
            } catch (IllegalStateException | UnsupportedOperationException e) {
                //WidgetHelper.showTips(this, ResourceTable.String_tips_mail_continue_failed);
                LogUtil.info(TAG, "continue button click error==="+e.getMessage());
            }
            dialog.hide();

            imgFind.setPixelMap(ResourceTable.Media_qianyi0);
            Sprite sprite = new Sprite(imgFind.getPixelMapHolder());
            this.btnFind = new Button(sprite);
            //startTimer();
        });
        dialog.show();


    }

    public void findClick2() {
        // 设置过滤设备类型
        ExtraParams params = new ExtraParams();
        String[] devTypes = new String[]{ExtraParams.DEVICETYPE_SMART_PAD, ExtraParams.DEVICETYPE_SMART_PHONE};
        params.setDevType(devTypes);
        String jsonParams = "{'filter':{'commonFilter':{'system':{'harmonyVersion':'2.0.0'},'groupType':'1|256','curComType': 0x00030004,'faFilter':'{\"targetBundleName\": \"com.example.daxiguaforharmony\"}'}},'transferScene':1,'remoteAuthenticationDescription': '拉起HiVision扫描弹框描述','remoteAuthenticationPicture':''}";
        params.setJsonParams(jsonParams);

        // 显示选择设备列表
        continuationRegisterManager.showDeviceList(abilityToken, params, null);
        if (selectDeviceId != null) {
            // 用户点击后发起迁移流程
            continueAbility(selectDeviceId);
        }
    }

}
